package demo.netty.netty.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;

public class ChineseProverbServer {


    public static void main(String[] args) {
        new ChineseProverbServer().bind(8080);
    }

    public void bind(int port) {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                .group(workGroup)
                .channel(NioDatagramChannel.class)
                //设置Socket参数支持广播
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChineseProverbHandler());
            bootstrap.bind(port).channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }


    public static class ChineseProverbHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        private static final String[] DICTIONARY = {"只要功夫深，铁棒磨成针。", "洛阳亲友如想问，一片冰心在玉壶"};

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            //将内容转换为字符串
            String req = msg.content().toString(StandardCharsets.UTF_8);
            System.out.println("请求数据：" + req);
            if ("谚语字典查询?".equals(req)) {
                ByteBuf byteBuf = Unpooled.copiedBuffer("谚语查询结果：" + nextQuote(), StandardCharsets.UTF_8);
                // msg.sender() 获取发送的ip和端口
                DatagramPacket returnPacket = new DatagramPacket(byteBuf, msg.sender());
                ctx.writeAndFlush(returnPacket);
            }
        }

        private String nextQuote() {
            int nextInt = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
            return DICTIONARY[nextInt];
        }
    }


}
